package leetcode_1_20;

public class romanToInt_13 {
    /**
     * 罗马数字转字符
     * MCMXCIV
     * 1994
     * @param s
     * @return
     */
    public static int romanToInt(String s) {
        int ans=0,
                S_index=0;
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        //由高到低排列特殊数值
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        //由高到低
        //同理，这次去除字符串
        for(int i=0;i <symbols.length;i++){
            int n=symbols[i].length();        //得到匹配字符串的位数，即1或者2
            if(S_index > s.length()-1)
                break;
            if(n==1) {                                 //一位字符直接遍历数量加对应的数值
                while (symbols[i].charAt(0)==( s.charAt(S_index) )){
                    S_index++;
                    ans+=values[i];
                    if(S_index > s.length()-1)
                        break;
                }
            }else {                                      //两位字符不需要while遍历，只会出现一次
                if( S_index==s.length()-1)//正好到了字符的最后一位时，不可能匹配两位字符,循环匹配其他罗马字符
                    continue;
                if(symbols[i].charAt(0)==( s.charAt(S_index) ) &&
                        symbols[i].charAt(1)==( s.charAt(S_index+1) )){      //下两位罗马字符中是否和其匹配
                    S_index+=2;
                    ans+=values[i];
                }
            }
        }
        return ans;
    }
}
